{% extends "dissemin/details.html" %}

{% load author %}
{% load domain %}
{% load statuses %}
{% load doi %}
{% load i18n %}
{% load static %}
{% load crispy_forms_tags %}

{% block headTitle %}
{% trans "Depositing" %} "{{ paper.title }}"
{% endblock %}

{% block bodyTitle %}
{% trans "Depositing" %} "{{ paper.title }}"
{% endblock %}

{% block extra_head %}
    <script src="{% static "libs/jquery.ui.widget.js" %}"></script>
    <script src="{% static "libs/jquery.iframe-transport.js" %}"></script>
    <script src="{% static "libs/jquery.fileupload.js" %}"></script>
    <script src="{% static "libs/upload.js" %}"></script>

    <link rel="stylesheet" href="{% static "css/upload.css" %}" />
    <link rel="stylesheet" href="{% static "css/deposit.css" %}" />
    <!-- repository-specific JS and CSS -->
    {% for repo_proto in available_repositories %}
        {{ repo_proto.1.get_form.media }}
    {% endfor %}
{% endblock %}

{% block jsScript %}
yl = {};
yl.jQuery = $;
$(function() {
    $('#waitingArea').hide();
    $('#uploadFileId').val('');
    
    /* Prefetched fields */
    function initPrefetch(p) {
        {% trans "Trying to fill this field automatically for you..." as trying_fill %}
        p.text("{{ trying_fill|escapejs }}");
        field = $("#"+p.data("fieldid"));
        objid = $("input[name="+p.data("objfieldname")+"]").val();
        field.prop('disabled', true);
        $.get(p.data("callback"),
            {"field":p.data("fieldname"),
            "id":objid}, null, 'json').fail(
            function(data) {
                {% trans "Sorry, we could not fill this for you." as sorry %}
                p.text('{{ sorry|escapejs }}');
                field.prop('disabled', false);
            }
        ).done(
            function(data) {
                if(!data['success']) {
                p.text('{{ sorry|escapejs }}');
                } else {
                    p.text('');
                }
                field.prop('disabled', false);
                field.val(data['value']);
            }
        );        
    }

    /* Autocomplete */
    function customTemplateResult(x) {
	var $result = $('<span>');
	$result.html(x.result);
	return $result;
    }
    function customTemplateSelection(x) {
	return x.selection;
    }
    
    // taken from django-autocomplete-light	
    function add_forwards(element) {
        var forward = element.attr('data-autocomplete-light-forward');
        if (forward !== undefined) {
            forward = forward.split(',');

            var prefix = $(element).getFormPrefix();
            var data_forward = {};

            for (var key in forward) {
                // First look for this field in the inline
                var $field = $('[name=' + prefix + forward[key] + ']');
                if (!$field.length)
                    // As a fallback, look for it outside the inline
                    $field = $('[name=' + forward[key] + ']');
                if ($field.length)
                    data_forward[forward[key]] = $field.val();
            }

            return JSON.stringify(data_forward);
        }
    }

    $(document).on('autocompleteLightInitialize',
    '[data-autocomplete-light-function=select2-customTemplate]', function() {
        var element = $(this);

        // This widget has a clear button
        $(this).find('option[value=""]').remove();

        var ajax = null;
        if ($(this).attr('data-autocomplete-light-url')) {
            ajax = {
                url: $(this).attr('data-autocomplete-light-url'),
                dataType: 'json',
                delay: 250,

                data: function (params) {
                    var data = {
                        q: params.term, // search term
                        page: params.page,
                        create:
element.attr('data-autocomplete-light-create') &&
!element.attr('data-tags'),
                        forward: add_forwards(element)
                    };

                    return data;
                },
                processResults: function (data, page) {
                    if (element.attr('data-tags')) {
                        $.each(data.results, function(index, value) {
                            value.id = value.text;
                        });
                    }

                    return data;
                },
                cache: true
            };
        }

        $(this).select2({
            tokenSeparators: element.attr('data-tags') ? [','] : null,
            debug: true,
            placeholder: '',
            minimumInputLength: 0,
            allowClear: ! $(this).is('required'),
            templateResult: customTemplateResult,
            templateSelection: customTemplateSelection,
            ajax: ajax,
        });

        $(this).on('select2:selecting', function (e) {
            var data = e.params.args.data;

            if (data.create_id !== true)
                return;

            e.preventDefault();

            var select = $(this);

            $.ajax({
                url: $(this).attr('data-autocomplete-light-url'),
                type: 'POST',
                dataType: 'json',
                data: {
                    text: data.id,
                    forward: add_forwards($(this))
                },
                beforeSend: function(xhr, settings) {
                    xhr.setRequestHeader("X-CSRFToken",
document.csrftoken);
                },
                success: function(data, textStatus, jqXHR ) {
                    select.append(
                        $('<option>', {value: data.id, selection:
data.selection, selected: true, result: data.result})
                    );
                    select.trigger('change');
                    select.select2('close');
                }
            });
        });

    });

    /* Dynamic selection of repositories */

    // functions that should be run every time we replace the form
    function init() {
	$('.prefetchingFieldStatus').each(function(i,prefetch) {
	    initPrefetch($(prefetch));
	});
	$('[data-autocomplete-light-function=select2-customTemplate]').trigger('autocompleteLightInitialize');
    }
    init(); // for the initial repository

    function updateMetadataForm(selected) {
        if(selected.val()) {
        $.get("{% url 'ajax-getMetadataForm' %}", data={'paper':{{ paper.id }},'repository':selected.val()}
            ).done(
                function(data) {
                    $("#repositoryMetadataForm").empty();
                    if('status' in data && data['status'] == 'success') {
                        $("#repositoryMetadataForm").append(data['form']);
			init();
                    } else if ('message' in data) {
                        $("#repositoryMetadataForm").append("<p>"+data["message"]+"</p>");
                    }
                }
            ).fail(
                function(data) {
                });
        }
    }

    $('.helpPopover').popover({trigger: "hover"});

    /* Panels */
    function collapseWithInline(input_name, callback) {
        $('#option'+input_name).collapse({
            parent:$('#'+input_name+'Options'),
            toggle:false,
            }).on('show.bs.collapse', function () {
            $('#'+input_name+'Inline').empty();
        }).on('hidden.bs.collapse', function () {
            var selected = $("input[type='radio'][name='radio"+input_name+"']:checked");
            if(selected.length > 0) {
            $('#'+input_name+'Inline').append($('#hiddenInline'+input_name+'-'+selected.val()).clone());
            }
            if(callback != null) {
                callback(selected);
            }
        });
        $("input[type='radio'][name='radio"+input_name+"']").click(function(){
            $('#option'+input_name).collapse('hide');
            $('#error-radio'+input_name).removeClass('error').empty();
        });
    }

    collapseWithInline('UploadType', null);
    collapseWithInline('Repository', updateMetadataForm);

    {% if request.GET.type %}
        $('#optionUploadType').collapse('hide');
    {% endif %}
});

    /* Submitting the deposit */
    function depositPaper() {
       var data = $('#depositForm').serialize();
       $('.error').removeClass('error').empty()
       $('#waitingArea,.submitDeposit').toggle();

       $.post('{% url 'ajax-submitDeposit' paper.pk %}', data, null, 'json').fail(
            function(data) {
                var errorText = '';
                if(!data.responseJSON) {
                    {% trans "Dissemin encountered an error, please try again later." as errormsg %}
                    errorText = "{{ errormsg|escapejs }}";
                } else {
                    error = data.responseJSON;
                    if('message' in error) {
                        errorText = error['message']
                    }
                    if('form' in error) {
                        errors = error['form']
                        if('file_id' in errors) {
                            $('#globalError').addClass('error').text(errors['file_id'][0]); 
                        }
                        if('radioUploadType' in errors) {
                            $('#error-radioUploadType').addClass('error').text(errors['radioUploadType'][0]);
                            $('#optionUploadType').collapse('show');
                        }
                    }
                    if('form_html' in error) {
                        $('#repositoryMetadataForm').html(error['form_html']);
                        $('#optionMetadata').collapse('show');
                    }
                }
                if(errorText) {
                    $('#depositError').addClass('error').text(errorText);
                }
                $('#waitingArea,.submitDeposit').toggle();
            }).done(function(data) {
                var uploadId = data['upload_id'];
                window.location.replace('{% url 'paper' paper.pk paper.slug %}?deposit='+uploadId);
            });
    }
{% endblock %}

{% block lists %}
<div id="uploadIntro">
    <p>
        {% url 'tos' as tosurl %}
        {% blocktrans %}
            You can deposit the full text of your article. Dissemin will
            send it to a repository where it will be made freely available.
            By depositing your article via Dissemin,
            you agree to our <a href="{{ tosurl }}">terms of service</a>.
        {% endblocktrans %}
    </p>

    {% if not is_owner %}
    <div class="alert alert-danger" role="alert">
        <span class="glyphicon glyphicon-exclamation-sign"></span>
        {% blocktrans trimmed %}
        You do not appear to be one of the authors of this paper.
        By using this form, you certify that you have the permission to
        upload it on their behalf.
        {% endblocktrans %}
    </div>
    {% endif %}
    {% if not selected_protocol %}
    <div class="alert alert-danger" role="alert">
        <span class="glyphicon glyphicon-exclamation-sign"></span>
        {% blocktrans trimmed %}
        This paper cannot be deposited in any repository supported by
        Dissemin.
        {% endblocktrans %}
    </div>
    {% endif %}
</div>

<span class="detailsTitle">{% trans "Document" %}</span>
<div class="detailsContent uploadSection">
    {% include "upload/widget.html" %}
</div>

<form method="POST" action="javascript:depositPaper()" id="depositForm">
{% csrf_token %}
<input type="hidden" id="uploadFileId" name="file_id" />
<span class="detailsTitle">{% trans "Options" %}</span>
<div id="uploadOptions" class="panel-group detailsContent" role="tablist" aria-multiselectable="true">
    <div id="error-radioUploadType"></div>
    <div class="panel panel-default">
        <div class="panel-heading" role="tab" id="headingUploadType">
            <a role="button" data-toggle="collapse" data-parent="#UploadTypeOptions"
            href="#optionUploadType">{% trans "Upload type:" %}<span id="UploadTypeInline"></span></a>
        </div>
        <div id="optionUploadType" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingUploadType">
            <div class="panel-body">
                {% include "publishers/detailsPolicy.html" with publisher=paper.publisher mode="radio" %}
            </div>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading" role="tab" id="headingRepository">
            <span>
                <a role="button" data-toggle="collapse"
                  data-parent="#uploadOptions" href="#optionRepository" aria-expanded="true"
                        aria-controls="optionRepository">{% trans "Repository:" %}<span id="RepositoryInline"></span></a>
            </span>
        </div>
        <div id="optionRepository" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingRepository">
            <div class="panel-body">
                <div class="repositoryList">
                {% for repository in available_repositories %}
                {% with repository.0 as repo %}
                {% with repository.1 as proto %}
                <div class="repositoryItem {% if forloop.first %}firstItem{% endif %} {% if not proto %}disabledRepositoryItem{% endif %}">

                    {% if not repo.enabled %}
                    <div style="text-align: center">
                            {% trans "Coming soon:" context "This repository will be soon available in Dissemin" %}
                    </div>
                    {% endif %}
                    <div style="display:none">
                        <span id="hiddenInlineRepository-{{ repo.pk }}">
                            <span><strong>{{ repo.name }}</strong>
                            </span>
                        </span>
                    </div>
                    <div class="repositoryLogo">
                        <a href="#" target="_blank">
                            <img src="{{ repo.logo.url }}" alt="{{ repo.name }}" />
                        </a>
                    </div>
                        <div class="repositoryChoiceRadio">
                            <input id="radiorepo{{ repository.pk}}" type="radio" value="{{repo.pk}}"
                                name="radioRepository" {% if not proto %}disabled="disabled"{% endif %}
                                {% if repo == selected_repository %}checked="checked"{% endif %} />
                        </div>
                    <p>
                        {{ repository.0.description }}
                    </p>

                    <div style="clear:left"></div>
                </div>
                {% endwith %}
                {% endwith %}
                {% endfor %}
                </div>
            </div>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading" role="tab" id="headingMetadata">
            <span>
                 <a role="button" data-toggle="collapse"
                  data-parent="#uploadOptions" href="#optionMetadata" aria-expanded="true"
                  aria-controls="optionMetadata">{% trans "Metadata" %}</a>
            </span>
        </div>
        <div id="optionMetadata" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingMetadata">
            <div class="panel-body">
                <div id="repositoryMetadataForm">
                    {{ selected_protocol.get_form|crispy }}
                </div>
            </div>
        </div>
    </div>
</div>
<div id="depositError"></div>
<div id="uploadSubmitSection">
    <p class="submitDeposit"><button type="submit" id="submitDeposit" class="btn btn-lg btn-primary"><span class="glyphicon glyphicon-circle-arrow-up"></span> {% trans "Deposit" %}</button></p>
    <div id="waitingArea">
        <span>{% trans "Processing deposit..." %}</span> <span class="waitingBird"><img src="{% static "img/animated-bird.gif" %}" /></span> <span>{% trans "please wait..." %}</span>
    </div>
</div>
</form>
{% endblock %}

{% block details %}
{% include "papers/paperDetails.html" with paper=paper %}

{% endblock %}

